package com.order.itemcategoryproject.controller;

import com.order.itemcategoryproject.pojo.DBlOrderHdOnline;
import com.order.itemcategoryproject.pojo.dArcItem;
import com.order.itemcategoryproject.pojo.dArcStaff;
import com.order.itemcategoryproject.pojo.dBlOrderDtOnline;
import com.order.itemcategoryproject.service.DBlOrderDtOnlineService;
import com.order.itemcategoryproject.service.DBlOrderHdOnlineService;
import com.order.itemcategoryproject.service.dArcItemService;
import com.order.itemcategoryproject.service.dArcStaffService;
import com.order.itemcategoryproject.utils.AjaxResult;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.order.itemcategoryproject.utils.ParseUrl.getUrl;
import static com.order.itemcategoryproject.utils.generateFour.generateFourDigitRandom;

@RestController
@RequestMapping("/order")
public class DBlOrderHdOnlineController {

    @Resource
    private DBlOrderHdOnlineService DBlOrderHdOnlineService;
    @Autowired
    private DBlOrderDtOnlineService DBlOrderDtOnlineService;
    @Autowired
    private dArcItemService dArcItemService;
    @Autowired
    private dArcStaffService dArcStaffService;


    @PostMapping("/insertOrderInfo")
    public AjaxResult insertOrderInfo(@RequestBody DBlOrderHdOnline dBlOrderHdOnline, HttpServletRequest request) {

        // 1、获取路径参数
        String queryString = request.getQueryString();
        String staffID = getUrl(queryString, "StaffID");

        if (StringUtils.isBlank(staffID)) {
            return AjaxResult.error("参数未被定义!!!!!!");
        }

        if (ObjectUtils.isEmpty(dBlOrderHdOnline)) {
            return AjaxResult.error("当前操作有误，请联系信息部赵光明!!!!!");
        }

        // staffID不为空，那么就获取该客户信息
        dArcStaff staffInfoByStaId = dArcStaffService.getStaffInfoByStaId(staffID);
        // 获取到当前对象之后，判断当前对象是否存在，再次判断当前对象是否是国内客户或者国际客户
        String orderId = null;
        if (ObjectUtils.isNotEmpty(staffInfoByStaId) && StringUtils.isNotBlank(staffInfoByStaId.getCus_segmentation())) {
            // 判断当前对象的顾客类型是否已经完善
            // 如果顾客类型为空，那么当前对象并不是国际客户或者国内客户，看是否需要完善信息
            if ("国际".equals(staffInfoByStaId.getCus_segmentation())) {
                // 随机生成四位订单号并且拼接门店编号
                orderId = generateFourDigitRandom();
                Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
                dBlOrderHdOnline.setOrderId(orderId);
                dBlOrderHdOnline.setOrderGenDate(currentTimestamp);
                dBlOrderHdOnline.setCreateStaff(staffInfoByStaId.getStaffName());
                dBlOrderHdOnline.setCustomerCode(staffID);
                dBlOrderHdOnline.setCusSegmentation(staffInfoByStaId.getCus_segmentation());
            } else if ("国内".equals(staffInfoByStaId.getCus_segmentation())){
                // 随机生成四位订单号并且拼接门店编号
                orderId = generateFourDigitRandom() + "-" + dBlOrderHdOnline.getStoreId();
                Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
                dBlOrderHdOnline.setOrderId(orderId);
                dBlOrderHdOnline.setOrderGenDate(currentTimestamp);
                dBlOrderHdOnline.setCreateStaff(staffInfoByStaId.getStaffName());
                dBlOrderHdOnline.setCustomerCode(staffID);
                dBlOrderHdOnline.setCusSegmentation(staffInfoByStaId.getCus_segmentation());
            }
        } else {
            return AjaxResult.error("为获取到当前对象，请检查当前对象是否已经存在或者顾客类型没有完善!!!!");
        }


        if (ObjectUtils.isNotEmpty(dBlOrderHdOnline) && StringUtils.isNotBlank(dBlOrderHdOnline.getOrderId())) {
            // 首先判断当前订单号是否已经存在表中
            DBlOrderHdOnline orderinfo = DBlOrderHdOnlineService.getOrderinfoByOrderId(dBlOrderHdOnline.getOrderId());
            // 通过当前订单号获取到当前订单信息，是否存在表中
            if (ObjectUtils.isNotEmpty(orderinfo)) {
             return AjaxResult.error("当前订单号已存在，请尝试再次操作!!!");
            }
        }
        int effectLine = DBlOrderHdOnlineService.insertOrderInfo(dBlOrderHdOnline);

        if (effectLine < 1) {
            return AjaxResult.error("添加失败!!!!!!");
        }

        return AjaxResult.success(effectLine);
    }


    /**
     * 根据制单人编号获取该制单人创建的订单
     *
     * @param request
     * @return
     */
    @GetMapping("/getOrderInfoByCreateStaff")
    public AjaxResult getOrderInfoByCreateStaffId(HttpServletRequest request) {
        String queryString = request.getQueryString();
        String staffID = getUrl(queryString, "StaffID");
        if (StringUtils.isEmpty(staffID)) {
            return AjaxResult.error("当前操作有误，请联系信息部!!!!!");
        }

        // 根据staffID获取客户名称
        dArcStaff staffInfo = dArcStaffService.getStaffInfoByStaId(staffID);
        if (ObjectUtils.isEmpty(staffInfo)) {
            return AjaxResult.error("为获取到该客户信息!!!!");
        }

        // 获取到该制单人下所有的订单信息
        return AjaxResult.success(DBlOrderHdOnlineService.getOrderInfoByStaffId(staffInfo.getStaffName()));
    }


    /**
     * 根据订单编号获取订单信息
     *
     * @param orderId
     * @return
     */
    @GetMapping("/getOrderInfoByOrderId/{orderId}/{currentLanguage}")
    public AjaxResult getOrderInfoByOrderId(@PathVariable String orderId, @PathVariable String currentLanguage) {
        if (StringUtils.isEmpty(orderId)) {
            return AjaxResult.error("当前操作不正确，请联系信息部!!!!");
        }

        HashMap<Object, Object> orderInfoResultMap = new HashMap<>();

        // 根据订单号获取订单信息
        DBlOrderHdOnline orderinfoByOrderId = DBlOrderHdOnlineService.getOrderinfoByOrderId(orderId);

        // 通过订单编号获取该订单下所有明细信息
        List<dBlOrderDtOnline> allOrderDetailByOrderId = DBlOrderDtOnlineService.getAllOrderDetailByOrderId(orderId);

        if (ObjectUtils.isEmpty(allOrderDetailByOrderId)) {
            int effectLine = DBlOrderHdOnlineService.updateOrderTotalNumAndTotalPrice(orderId);
            if (effectLine > 0) {
                orderinfoByOrderId = DBlOrderHdOnlineService.getOrderinfoByOrderId(orderId);
            }
        } else {
            int totalNum = allOrderDetailByOrderId.stream()
                    .mapToInt(dBlOrderDtOnline::getItemOrderNum)
                    .sum();

            double totalPrice = allOrderDetailByOrderId.stream()
                    .mapToDouble(detail -> detail.getItemOrderNum() * detail.getItemPrice())
                    .sum();

            // 订单总体积（当前明细里所有商品的体积之和）
            double totalVolume = allOrderDetailByOrderId.stream()
                    .mapToDouble(detail -> detail.getItemVolume() * detail.getItemOrderNum())
                    .sum();

            // 订单总重量
            double totalWeight = allOrderDetailByOrderId.stream()
                    .mapToDouble(detail -> detail.getItemWeight() * detail.getItemOrderNum())
                    .sum();

            // 使用 BigDecimal 保留两位小数
            BigDecimal totalPriceBD = BigDecimal.valueOf(totalPrice);
            totalPriceBD = totalPriceBD.setScale(2, RoundingMode.HALF_UP);
            // 使用BigDecimal保留六位小数 订购商品明细信息的总体积计算
            BigDecimal totalVolumeBD = BigDecimal.valueOf(totalVolume);
            totalVolumeBD = totalVolumeBD.setScale(6, RoundingMode.HALF_UP);

            // 使用BigDecimal保留六位小数 订购商品明细信息的总重量计算
            BigDecimal totalWeightBD = BigDecimal.valueOf(totalWeight);
            totalWeightBD = totalWeightBD.setScale(6, RoundingMode.HALF_UP);
            DBlOrderHdOnlineService.updateOrderInfoByOrderId(orderId, totalNum, totalPriceBD.doubleValue(), totalVolumeBD.doubleValue(), totalWeightBD.doubleValue());
            // 更新完之后在重新获取当前订单
            orderinfoByOrderId = DBlOrderHdOnlineService.getOrderinfoByOrderId(orderId);
        }

        // 根据订单号和客户编号获取该订单下所有订单明细
        // 从而去渲染该订单下明细信息的订单 去商品主表中检索数据
        if (ObjectUtils.isNotEmpty(orderinfoByOrderId) && ObjectUtils.isNotEmpty(allOrderDetailByOrderId)) {
            // 根据制单人名称获取制单人信息
            dArcStaff dArcStaff = dArcStaffService.getstaffInfoByName(orderinfoByOrderId.getCreateStaff());
            List<dArcItem> dArcItems = null;
            if (ObjectUtils.isNotEmpty(dArcStaff) && StringUtils.isNotBlank(dArcStaff.getCus_segmentation())) {
                dArcItems = dArcItemService.selectAllItemInfoByOrderIdAndCreateStaffId(orderId, dArcStaff.getStaffName(),
                        dArcStaff.getStaffId(), currentLanguage, dArcStaff.getCus_segmentation());
            } else {
                return AjaxResult.error("未获取到国际客户，当前还未对国内客户资料完善,终止此操作!!!!!!");
            }
            for (int i = 0; i < dArcItems.size(); i++) {
                for (int j = 0; j < allOrderDetailByOrderId.size(); j++) {
                    if (!dArcItems.get(i).getItemId().equals(allOrderDetailByOrderId.get(j).getItemId())) {
                        continue;
                    }
                    dArcItems.get(i).setOrderQuantity(allOrderDetailByOrderId.get(j).getItemOrderNum());
                }
            }
            if (ObjectUtils.isNotEmpty(dArcItems)) {
                orderInfoResultMap.put("itemList", dArcItems);
            }
        }
        if (ObjectUtils.isEmpty(orderinfoByOrderId)) {
            return AjaxResult.error("为获取到该订单信息!!!!!!");
        }
        orderInfoResultMap.put("orderInfo", orderinfoByOrderId);

        return AjaxResult.success(orderInfoResultMap);
    }


    /**
     * 通过订单编号获取订单信息
     * 更新信息
     *
     * @param orderId
     * @return
     */
    @GetMapping("/selectOrderMsgByOrderId/{orderId}")
    public AjaxResult selectOrderInfoByOrderId(@PathVariable String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return AjaxResult.error("参数未被定义!!!!!!!");
        }
        // 根据订单号获取订单信息
        DBlOrderHdOnline orderinfo = DBlOrderHdOnlineService.getOrderinfoByOrderId(orderId);
        if (ObjectUtils.isEmpty(orderinfo)) {
            return AjaxResult.error("为获取到该对象!!!!!");
        }

        return AjaxResult.success(orderinfo);
    }


    /**
     * 根据订单编号更新当前订单状态
     *
     * @param orderId
     * @return
     */
    @PutMapping("/updateOrderStatus/{orderId}")
    public AjaxResult updateOrderStatusByOrderId(@PathVariable String orderId) {
        // 如果订单编号为空，则直接返回
        if (StringUtils.isBlank(orderId)) {
            return AjaxResult.error("参数未被定义，请联系信息部!!!!!");
        }

        // 根据订单获取订单信息
        DBlOrderHdOnline orderInfo = DBlOrderHdOnlineService.getOrderinfoByOrderId(orderId);
        if ("001".equals(orderInfo.getOrderStatus())) {
            return AjaxResult.error("当前订单号为【" + orderId + "】已经下单完成，请勿重复操作!!!!!!");
        }

        int effectLine = DBlOrderHdOnlineService.updateOrderStatusByOrderId(orderId);
        // 如果受影响行数为1，证明修改成功
        if (effectLine > 0) {
            return AjaxResult.success("当前订单号为【" + orderId + "】已下单成功!!!!!");
        } else {
            return AjaxResult.error("当前订单号为【" + orderId + "】未下单成功!!!!!");
        }
    }


    /**
     * 通过订单编号将订单以及订单明细信息删除
     *
     * @param orderId
     * @return
     */
    @DeleteMapping("/deleteOrderInfoByOrderId/{orderId}")
    @Transactional
    public AjaxResult deleteOrderInByOrderId(@PathVariable String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return AjaxResult.error("参数未被定义!!!!!!");
        }

        try {
            // 根据订单编号获取订单信息
            DBlOrderHdOnline orderInfo = DBlOrderHdOnlineService.getOrderinfoByOrderId(orderId);
            if (orderInfo == null) {
                return AjaxResult.error("订单不存在！");
            }

            // 如果订单已完成，不允许删除
            if ("001".equals(orderInfo.getOrderStatus())) {
                return AjaxResult.error("当前订单【" + orderId + "】处于已下单状态，不可进行修改!!!!!!");
            }

            // 根据订单编号获取明细信息
            List<dBlOrderDtOnline> allOrderDetailByOrderId = DBlOrderDtOnlineService.getAllOrderDetailByOrderId(orderId);

            if (ObjectUtils.isNotEmpty(allOrderDetailByOrderId)) {
                // 删除订单明细
//                int detailDeleteCount = DBlOrderDtOnlineService.deleteOrderInfoDetailByOrderId(orderId);
                int detailDeleteCount = DBlOrderDtOnlineService.updateOrderDetailByOrderId(orderId);
                // 删除订单信息
//                int orderDeleteCount = DBlOrderHdOnlineService.deleteOrderInfoByOrderId(orderId);
                int orderDeleteCount = DBlOrderHdOnlineService.updateOrderByOrderId(orderId);

                if (detailDeleteCount > 0 && orderDeleteCount > 0) {
                    return AjaxResult.success("删除成功!!!!!");
                } else {
                    return AjaxResult.error("删除失败!!!!!");
                }
            } else {
                // 删除订单信息
//                int orderDeleteCount = DBlOrderHdOnlineService.deleteOrderInfoByOrderId(orderId);
                int orderDeleteCount = DBlOrderHdOnlineService.updateOrderByOrderId(orderId);
                if (orderDeleteCount > 0) {
                    return AjaxResult.success("删除成功!!!!!");
                } else {
                    return AjaxResult.error("删除失败!!!!!");
                }
            }
        } catch (Exception e) {
            // 捕获异常并返回错误消息
            return AjaxResult.error("删除订单失败: " + e.getMessage());
        }
    }


    /**
     * 根据订单编号更新此订单内容
     *
     * @param orderId
     * @param content
     * @return
     */
    @PutMapping("/udateRemark")
    public AjaxResult updateOrderRemarkByOrderId(@RequestParam("orderId") String orderId, @RequestParam("content") String content) {
        if (StringUtils.isBlank(orderId) || StringUtils.isBlank(content)) {
            return AjaxResult.error("参数未被定义!!!!!!!");
        }

        int effectLine = DBlOrderHdOnlineService.updateRemarkContentByOrderId(orderId, content);
        // 如果行数大于0，证明修改成功
        if (effectLine > 0) {
            return AjaxResult.success("已为该订单【" + orderId + "】添加备注!!!!!");
        } else {
            return AjaxResult.error("添加失败!!!!!!");
        }
    }


    /**
     * 根据客户编号获取当前客户下最新创建的订单
     *
     * @param request
     * @return
     */
    @GetMapping("/selectNewOrderInfoDesc")
    public AjaxResult selectNewOrderInfoDescDate(HttpServletRequest request) {
        String queryString = request.getQueryString();
        String staffID = getUrl(queryString, "StaffID");
        if (StringUtils.isBlank(staffID)) {
            return AjaxResult.error("参数未被定义");
        }
        dArcStaff info = dArcStaffService.getStaffInfoByStaId(staffID);
        DBlOrderHdOnline dBlOrderHdOnline = null;
        if (ObjectUtils.isNotEmpty(info)) {
            dBlOrderHdOnline = DBlOrderHdOnlineService.selectNewOrderInfoDesc(info.getStaffName());
        }
        if (ObjectUtils.isEmpty(dBlOrderHdOnline)) {
            return AjaxResult.error("为获取到当前对象!!!!!");
        }
        return AjaxResult.success(dBlOrderHdOnline);
    }


    /**
     * 根据订单编号以及客户名称来更新预计付款时间
     *
     * @param orderId
     * @param createStaffId
     * @param esPaymentDate
     * @return
     */
    @PutMapping("/updateOrderEsTimeByIdAndCuId")
    public AjaxResult updateOrderEsPaymentDateByIdAndCusId(@RequestParam("orderId") String orderId,
                                                           @RequestParam("createStaffId") String createStaffId,
                                                           @RequestParam("esPaymentDate") Date esPaymentDate) {
        if (StringUtils.isBlank(orderId) || StringUtils.isBlank(createStaffId) || ObjectUtils.isEmpty(esPaymentDate)) {
            return AjaxResult.error("参数未被定义或操作有误，请联系信息部!!!!!!");
        }

        int effectLine = DBlOrderHdOnlineService.updateEsPaymentTimeByOrderIdAndCreateStaffId(orderId, createStaffId, esPaymentDate);

        if (effectLine > 0) {
            // 更新成功之后获取更新过后的订单
            DBlOrderHdOnline orderinfo = DBlOrderHdOnlineService.getOrderinfoByOrderId(orderId);
            return AjaxResult.success("已经将该订单【" + orderId + "】的预计付款时间延期为【" + esPaymentDate + "】!!!!!!", orderinfo);
        } else {
            return AjaxResult.error("延期当前订单【" + orderId + "】的预计付款时间失败!!!!!");
        }

    }


}
